package top.digger.web.cron;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import top.digger.web.entity.DaHuaRoleInfo;
import top.digger.web.mapper.DaHuaRoleInfoMapper;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;

/**
 * select id, concat('https://xy2.cbg.163.com/equip?s=',server_id, '&eid=', eid) from da_hua_role_info order by id asc
 */
@Configuration
@EnableScheduling
public class XYTaoBaoGeCronTask {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public DaHuaRoleInfoMapper daHuaRoleInfoMapper;

    @Scheduled(cron = "0 0 2 * * ?")
    public void test(){
        HttpClient httpClient = init();
        int page = 1;
        boolean lastPage = false;
        while (!lastPage){
            String xyUrl = "https://xy2.cbg.163.com/cgi-bin/recommend.py?";
            String callBack = "Request.JSONP.request_map.request_1";
            Long _time = System.currentTimeMillis();

            int roleLevelMin = 4178;
            String random = "Sat%20Nov%2020%202021%2023%3A28%3A55%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)";
            int serverType = 3;
            StringBuffer sb = new StringBuffer();
            sb.append(xyUrl)
//                    .append("callback").append("=").append(callBack)
                    .append("_").append("=").append(_time)
                    .append("&pass_fair_show").append("=").append(1)
                    .append("&act").append("=").append("recommd_by_role")
                    .append("&page").append("=").append(page)
                    .append("&price_min").append("=").append(0)
                    .append("&price_max").append("=").append(100000000)
                    .append("&role_level_min").append("=").append(roleLevelMin)
                    .append("&server_type").append("=").append(serverType)
                    .append("&max_fest_point").append("=").append(50)
                    .append("&talent").append("=").append(50)
                    .append("&child_qinmi_plus_xiaoxin").append("=").append(800)
                    .append("&achievement").append("=").append(4800)
                    .append("&has_second_rei").append("=").append(1)
                    .append("&count").append("=").append(15)
//            .append("&random").append("=").append(random)
                    .append("&search_type=role_search&view_loc=overall_search");
            logger.info(sb.toString());
            HttpGet httpGet = new HttpGet(sb.toString());
//        httpGet.setHeader("authority", "xy2.cbg.163.com");
//        httpGet.setHeader("method", "GET");
//        httpGet.setHeader("ec-ch-ua", "\"Google Chrome\";v=\"95\", \"Chromium\";v=\"95\", \";Not A Brand\";v=\"99\"");
//        httpGet.setHeader("sec-ch-ua-mobile", "?0");
//        httpGet.setHeader("sec-ch-ua-platform", "macOS");
//        httpGet.setHeader("referer", "https://xy2.cbg.163.com/cgi-bin/equipquery.py?act=show_overall_search");
//        httpGet.setHeader("accept-encoding", "gzip, deflate, br");
//        httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
//        httpGet.setHeader("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
//        httpGet.setHeader("referer", "0");
//        httpGet.setHeader("cookie", "return_url=; msg_box_flag=1; fingerprint=adlizsno2p7mil0o; _ntes_nnid=63017ff21e1ff29b1f244f949c669d24,1636986034827; _ntes_nuid=63017ff21e1ff29b1f244f949c669d24; timing_user_id=time_8Opcsi40xa; _external_mark=www.baidu.com; area_td_id=1; area_id=3; cur_servername=%25E5%25A4%25AA%25E5%2588%259D%25E5%25B9%25BB%25E5%25A2%2583; reco_sid=Etc_R6caqZYFEixiee94aLZir1kTa-FxyUP3rJg_; no_login_mark=1; trace_session_id=017D3DF6-CCC9-9637-442D-E0C5341B59A4; sid=ZINe61sPmazVq9MhtZz4gavdPTPdcTYlFYmWhVyV; last_login_serverid=405; wallet_data=%7B%22is_locked%22%3A%20false%2C%20%22checking_balance%22%3A%200%2C%20%22balance%22%3A%200%2C%20%22free_balance%22%3A%200%7D; latest_views=405_1787083; msg_box_flag=1; UserProvince=%u5168%u56FD");
//        httpGet.setHeader("path", "/cgi-bin/recommend.py?callback=Request.JSONP.request_map.request_1&_=1637426275315&pass_fair_show=1&act=recommd_by_role&page=1&price_min=0&price_max=100000000&role_level_min=4159&server_type=3&count=15&search_type=role_search&view_loc=overall_search");
//



//        :path: /cgi-bin/recommend.py?callback=Request.JSONP.request_map.request_1&_=1637422135921&pass_fair_show=1&act=recommd_by_role&page=1&price_min=0&price_max=100000000&role_level_min=4159&server_type=3&random=Sat%20Nov%2020%202021%2023%3A28%3A55%20GMT%2B0800%20(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)&count=15&search_type=role_search&view_loc=overall_search
//:scheme: https
//        accept: */*
//sec-fetch-dest: script
//sec-fetch-mode: no-cors
//sec-fetch-site: same-origin

            try {
                HttpResponse httpResponse = httpClient.execute(httpGet);
                String result = EntityUtils.toString(httpResponse.getEntity());
//                String resultJson = result.substring(36, result.length() - 1);
//            System.out.println(resultJson);
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                JSONArray dataJsonArray = jsonObject.getJSONArray("result");
                lastPage = jsonObject.getJSONObject("paging").getBoolean("is_last_page");
                for (int i = 0; i < dataJsonArray.size(); i++){
                    JSONObject data = dataJsonArray.getJSONObject(i);
                    String desc = data.getJSONObject("other_info").getString("desc");
                    int index = desc.indexOf("usernum") + 9;
                    StringBuffer idBuffer = new StringBuffer();
                    while ( Character.isDigit(desc.charAt(index))){
                        idBuffer.append(desc.charAt(index));
                        index++;
                    }

                    Integer id = Integer.valueOf(idBuffer.toString());

                    if (id > 10000000){
                        continue;
                    }
                    DaHuaRoleInfo dahuaRole = new DaHuaRoleInfo();
                    dahuaRole.setEid(data.getString("eid"));
                    dahuaRole.setServerId(data.getInteger("serverid"));
                    dahuaRole.setPrice(data.getString("price_desc"));
                    dahuaRole.setLevelDesc(data.getString("level_desc"));
                    dahuaRole.setServerName(data.getString("server_name"));
                    dahuaRole.setId(id);
                    daHuaRoleInfoMapper.insertOrUpdate(dahuaRole);

                }
                Thread.sleep(3000);

            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }

            page++;
        }

        logger.info("藏宝阁抓取end...");

    }

    public HttpClient init(){
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)//一、连接超时：connectionTimeout-->指的是连接一个url的连接等待时间
                .setSocketTimeout(5000)// 二、读取数据超时：SocketTimeout-->指的是连接上一个url，获取response的返回等待时间
                .setConnectionRequestTimeout(5000)
                .build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        return httpClient;
    }


    public HttpGet get(String url, Map<String, String> params){
        if (params != null){
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()){
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            url = url + "?" + sb.toString();
        }
        HttpGet httpGet = new HttpGet(url);
        return httpGet;
    }
}
